package com.zdd.ehe.service.impl;

import com.zdd.ehe.service.ISpiderService;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @title:
 * @author:
 * @description:
 * @createDate: 2023/3/18  22:10
 */
@Service
public class ISpiderServiceImpl implements ISpiderService {
    /**
     * 异步执行爬虫文件
     *
     * @param path
     * @return
     */
    @Override
    public Boolean executeAsyncTask(String path) {
        System.out.println("线程" + Thread.currentThread().getName() + " 执行爬虫任务");
        Runtime runtime = Runtime.getRuntime();
        String[] cmd = {"python" ,path};
        System.out.println(path);
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            runtime.exec(cmd).getInputStream(),
                            "GB2312"
                    )
            );
            String line;
            StringBuilder b = new StringBuilder();
            while ((line = br.readLine()) != null) {
                b.append(line).append("\n");
            }
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
        System.out.println("线程" + Thread.currentThread().getName() + " 执行爬虫任务结束");

        return Boolean.TRUE;
    }

    /*
    @Override
    public Boolean executeAsyncTask(String path) {
        try {
            System.out.println("线程" + Thread.currentThread().getName() + " 执行爬虫任务");
            String[] cmd = { "cmd.exe ","python" ,path};
            //System.out.println(path);
            Runtime.getRuntime().exec(cmd);

            System.out.println("线程" + Thread.currentThread().getName() + " 执行爬虫任务结束");
        }catch (Exception e){
            e.printStackTrace();
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }*/
}
